/**
 * JAVACC DEMO 1.0
 */
package com.apache.client.common;

import org.apache.commons.collections.map.CaseInsensitiveMap;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * description:  工具类
 *
 */
public class StringUtil {

    private StringUtil() {
        //StringUtil
    }

    /**
     * 将一个 JavaBean 对象转化为一个  Map
     *
     * @param bean 要转化的JavaBean 对象
     * @return 转化出来的  Map 对象
     * @exception IntrospectionException 如果分析类属性失败
     */
    public static Map convertBean(Object bean) throws IntrospectionException {
        Class type = bean.getClass();
        Map returnMap = new CaseInsensitiveMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                try {
                    Method readMethod = descriptor.getReadMethod();
                    Object result = readMethod.invoke(bean, new Object[0]);
                    if (!isEmpty(result)) {
                        returnMap.put(propertyName.toLowerCase(), result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return returnMap;
    }

    /**
     * 判断对象是否为空
     *
     * @param obj 传入的对象
     * @return 如果obj为空返回true，不为空返回false
     */
    private static boolean isEmpty(Object obj) {
        return obj == null;
    }
}
